import React, {useEffect, useState} from 'react';
import {
  View,
  Text,
  TextInput,
  Button,
  StyleSheet,
  Modal,
  TouchableOpacity,
  TouchableWithoutFeedback,
  Keyboard,
} from 'react-native';
import useHideTabBar from '../utils/useHideTabBar';
import API from '../Network/Api';
import {showToast} from '../utils/toastUtils';
import Toast from 'react-native-toast-message';
import {getData} from '../utils/storageUtils';
import theme from '../utils/theme';
import {CustomText} from '../customview/CustomText';
import {normalize} from '../utils/commonUtils';

let localPay = '';
let payLock = true;

const ServiceFeeTransferPage = ({navigation, route}) => {
  const {totalEarnings} = route.params;

  // 当前服务费余额，这里假设初始余额为 1000 元，可根据实际情况修改
  const [currentBalance, setCurrentBalance] = useState(totalEarnings);
  // 转账金额
  const [transferAmount, setTransferAmount] = useState('');
  // 对方手机号
  const [recipientPhone, setRecipientPhone] = useState('');
  // 支付密码
  const [paymentPassword, setPaymentPassword] = useState('');
  // 支付密码输入框模态框显示状态
  const [isPasswordModalVisible, setIsPasswordModalVisible] = useState(false);

  useHideTabBar(navigation);

  useEffect(() => {
    // 检查存储中的登录状态
    const checkLoginStatus = async () => {
      const userInfo = await getData('userInfoKey');
      if (userInfo) {
        if (userInfo.hasOwnProperty('payPassword')) {
          localPay = userInfo.payPassword;
        }
      }
    };

    checkLoginStatus();
  }, []);

  const handleTransfer = () => {
    const amount = parseFloat(transferAmount);
    if (isNaN(amount) || amount <= 0) {
      showToast({
        text2: '请输入有效的转账金额！',
      });
      return;
    }
    if (amount % 100 !== 0) {
      showToast({
        text2: '转账金额必须是 100 的倍数！',
      });
      return;
    }
    if (amount > currentBalance) {
      showToast({
        text2: '转账金额超过当前余额！',
      });
      return;
    }
    if (!recipientPhone || recipientPhone.length !== 11) {
      showToast({
        text2: '请输入有效的 11 位手机号',
      });
      return;
    }
    // 显示支付密码输入框模态框
    setIsPasswordModalVisible(true);
  };

  const confirmTransferWithPassword = () => {
    if (!payLock) {
      return;
    }
    // 这里可以添加对支付密码的验证逻辑，例如调用 API 验证密码
    if (!paymentPassword || paymentPassword.length < 6) {
      showToast({
        text2: '请输入有效的支付密码！',
        position: 'center',
      });
      payLock = true;
      return;
    }
    if (localPay !== paymentPassword) {
      showToast({
        text2: '支付密码错误！',
        position: 'center',
      });
      payLock = true;
      return;
    }
    API.feeTransferReq(recipientPhone, transferAmount)
      .then(response => {
        console.log('success', response);
        if (response.resultCode === '1') {
          showToast({
            text2: '转账成功！',
            visibilityTime: 1000,
          });
          setCurrentBalance(currentBalance - parseFloat(transferAmount));
          setTransferAmount('');
          setRecipientPhone('');
          setPaymentPassword('');
          setIsPasswordModalVisible(false);
        } else {
          showToast({
            type: 'error',
            text2: response.showMsg,
          });
        }
        payLock = true;
      })
      .catch(error => {
        console.log('error', error);
        payLock = true;
        showToast({
          type: 'error',
          text2: '转账失败！',
        });
      });
  };

  const dismissKeyboard = () => {
    Keyboard.dismiss();
  };

  return (
    <TouchableWithoutFeedback onPress={dismissKeyboard}>
      <View style={styles.container}>
        {/* 最上方可转账服务费 */}
        <CustomText style={styles.title}>可转账服务费（元）</CustomText>
        <CustomText style={styles.balanceText}>{currentBalance}</CustomText>

        {/* 转账金额输入框 */}
        <CustomText style={styles.label}>转账金额</CustomText>
        <TextInput
          allowFontScaling={false}
          style={styles.input}
          placeholder="请输入转账金额"
          keyboardType="numeric"
          value={transferAmount}
          onChangeText={text => setTransferAmount(text)}
        />

        {/* 手机号输入框 */}
        <CustomText style={styles.label}>请输入对方手机号</CustomText>
        <TextInput
          allowFontScaling={false}
          style={styles.input}
          placeholder="请输入对方手机号"
          keyboardType="phone-pad"
          value={recipientPhone}
          onChangeText={text => setRecipientPhone(text)}
        />

        {/* 确认转账按钮 */}
        <Button title="确认转账" onPress={handleTransfer} />

        {/* 支付密码输入框模态框 */}
        <Modal
          visible={isPasswordModalVisible}
          animationType="slide"
          transparent={true}>
          <View style={styles.modalContainer}>
            <View style={styles.modalContent}>
              <CustomText style={styles.modalTitle}>请输入支付密码</CustomText>
              <TextInput
                allowFontScaling={false}
                style={styles.input}
                placeholder="请输入支付密码"
                keyboardType="numeric"
                secureTextEntry
                value={paymentPassword}
                onChangeText={text => setPaymentPassword(text)}
              />
              <View style={styles.modalButtonContainer}>
                <TouchableOpacity
                  style={styles.modalButton}
                  onPress={confirmTransferWithPassword}>
                  <CustomText style={styles.modalButtonText}>确认</CustomText>
                </TouchableOpacity>
                <TouchableOpacity
                  style={styles.cancelButton}
                  onPress={() => setIsPasswordModalVisible(false)}>
                  <CustomText style={styles.modalButtonText}>取消</CustomText>
                </TouchableOpacity>
              </View>
            </View>
          </View>
        </Modal>
        <Toast />
      </View>
    </TouchableWithoutFeedback>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    padding: 20,
    backgroundColor: '#fff',
  },
  title: {
    fontSize: normalize(20),
    fontWeight: 'bold',
    marginBottom: 10,
  },
  balanceText: {
    fontSize: normalize(18),
    marginBottom: 20,
  },
  label: {
    fontSize: normalize(16),
    marginBottom: 5,
  },
  input: {
    borderWidth: 1,
    borderColor: '#ccc',
    padding: 10,
    marginBottom: 20,
    borderRadius: 5,
  },
  modalContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: 'rgba(0, 0, 0, 0.5)',
  },
  modalContent: {
    backgroundColor: '#fff',
    padding: 20,
    borderRadius: 10,
    width: '80%',
  },
  modalTitle: {
    fontSize: normalize(18),
    fontWeight: 'bold',
    marginBottom: 10,
  },
  modalButtonContainer: {
    flexDirection: 'row',
    justifyContent: 'space-around',
  },
  modalButton: {
    backgroundColor: theme.colors.primary,
    padding: 10,
    borderRadius: 5,
    width: '40%',
    alignItems: 'center',
  },
  cancelButton: {
    padding: 10,
    borderRadius: 5,
    width: '40%',
    alignItems: 'center',
    backgroundColor: '#bbb',
  },
  modalButtonText: {
    color: '#fff',
    fontSize: normalize(16),
  },
});

export default ServiceFeeTransferPage;
